package com.mazaiting.redeye.controller;

import com.mazaiting.redeye.config.GlobalConfig;
import com.mazaiting.redeye.domain.ImageBean;
import com.mazaiting.redeye.domain.Response;
import com.mazaiting.redeye.domain.ResponseCode;
import com.mazaiting.redeye.utils.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/***
 *
 *
 *                                                    __----~~~~~~~~~~~------___
 *                                   .  .   ~~//====......          __--~ ~~
 *                   -.            \_|//     |||\\  ~~~~~~::::... /~
 *                ___-==_       _-~o~  \/    |||  \\            _/~~-
 *        __---~~~.==~||\=_    -_--~/_-~|-   |\\   \\        _/~
 *    _-~~     .=~    |  \\-_    '-~7  /-   /  ||    \      /
 *  .~       .~       |   \\ -_    /  /-   /   ||      \   /
 * /  ____  /         |     \\ ~-_/  /|- _/   .||       \ /
 * |~~    ~~|--~~~~--_ \     ~==-/   | \~--===~~        .\
 *          '         ~-|      /|    |-~\~~       __--~~
 *                      |-~~-_/ |    |   ~\_   _-~            /\
 *                           /  \     \__   \/~                \__
 *                       _--~ _/ | .-~~____--~-/                  ~~==.
 *                      ((->/~   '.|||' -_|    ~~-/ ,              . _||
 *                                 -_     ~\      ~~---l__i__i__i--~~_/
 *                                 _-~-__   ~)  \--______________--~~
 *                               //.-~~~-~_--~- |-------~~~~~~~~
 *                                      //.-~~~--\
 *                               神兽保佑
 *                              代码无BUG!
 * @author mazaiting
 * @date 2019-06-28
 * @decription 文件上传控制器
 */
@Controller
@RequestMapping(GlobalConfig.UPLOAD)
public class UploadController {

    /**
     * 日志工具
     */
    private Logger mLog = LoggerFactory.getLogger(UploadController.class);
    /**
     * 静态访问路径
     */
    @Value("${file.staticAccessPath}")
    private String mStaticAccessPath;
    /**
     * 上传文件夹
     */
    @Value("${file.uploadFolder}")
    private String mUploadFolder;

    /**
     * 上传图片
     * @param multipartFiles 图片列表
     * @return 图片相关信息
     */
    @ResponseBody
    @PostMapping(GlobalConfig.UPLOAD_IMAGE)
    public Response<List<ImageBean>> upload(@RequestParam("file") MultipartFile[] multipartFiles) {
        mLog.debug(mStaticAccessPath);
        Response<List<ImageBean>> response = new Response<>();
        // 检测文件是否为空
        if (multipartFiles.length == 0) {
            response.setResponse(ResponseCode.ERROR, "文件列表不能为空");
            return response;
        }
        // 创建图片父文件夹
        File parentFile = new File(mUploadFolder);

        mLog.debug("文件本地路径: " + parentFile.getAbsolutePath());
        // 检测文件夹是否存在
        if (!parentFile.exists()) {
            // 如果不存在则创建
            boolean isSuccess = parentFile.mkdirs();
            mLog.debug("image 文件夹创建是否成功: " + isSuccess);
        }
//        StringBuilder sb = new StringBuilder();
        List<ImageBean> list = new ArrayList<>();
        // 标记是否有上传失败的文件
        boolean hasError = false;
        // 遍历文件
        for (MultipartFile originFile : multipartFiles) {
            // 获取文件名
            String filename = originFile.getOriginalFilename();
            mLog.debug("文件名: " + filename);
            // 检测文件是否为空
            if (originFile.isEmpty() || StringUtils.isEmpty(filename)) {
                hasError = true;
                ImageBean imageBean = new ImageBean();
                imageBean.setImageBean(false, filename, "文件为空");
                list.add(imageBean);
            } else {
                // 获取格式
                String formatName = FileUtils.getFormatName(originFile);
                // 创建文件
                String newFileName = System.currentTimeMillis() + "." + formatName;
                File dest = new File(parentFile, newFileName);

                try {
                    // 保存文件
                    originFile.transferTo(dest);
//                    sb.append("上传 ").append(filename).append(" 文件成功;");
                    list.add(new ImageBean(true, filename, newFileName));
                } catch (IOException e) {
                    e.printStackTrace();
                    hasError = true;
                    ImageBean imageBean = new ImageBean();
                    imageBean.setImageBean(false, filename, "保存失败");
                    list.add(imageBean);
//                    sb.append("上传 ").append(filename).append(" 文件失败;");
                }
            }
        }
        // 检测是否有上传失败的文件
        if (hasError) {
            response.setResponse(ResponseCode.ERROR, "上传失败", list);
        } else {
            response.setResponse(ResponseCode.SUCCESS, "上传成功", list);
        }
        return response;
    }

}
